//
//  ZPOauthViewController.swift
//  ZPWeibo
//
//  Created by zhangpeng on 16/4/17.
//  Copyright © 2016年 zhangpeng. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
//App Key：2054439017
//App Secret：8e21e280d41426bb3fde6e0c5c7dd675

class ZPOauthViewController: UIViewController {

    override func loadView() {
        view = webView
        
        webView.delegate = self
        //document.getElementById('userId').value = 'zhangpeng'
        //document.getElementById('passwd').value = '123456'
//        client_id	true	string	申请应用时分配的AppKey。
//        redirect_uri
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
       // print(url)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    //监听方法
    @objc private func cancle(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func auto(){
        
        print("自动填充按钮点击啦")
        //document.getElementById('userId').value = '937733253@qq.com'
        //document.getElementById('passwd').value = 'z+p591168'
        let jsString = "document.getElementById('userId').value = '\(ZPWeiboName)';document.getElementById('passwd').value = '\(ZPWeiboPassword)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //MARK: - 设置视图
    private func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
    }
    
    
    //设置导航栏
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
     
        
        navigationItem.title = "微博登陆"
    }
    //懒加载webView

    private lazy var webView = UIWebView()
}

extension ZPOauthViewController:UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // webView将要加载url的时候 会调用该方法 如果我们是使用代理方法 默认返回true
    // 如果我们叫他返回false 将不再加载该请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        

        
//        urlString?.hasPrefix(REDIRECT_URI)
        
        if let urlString = request.URL?.absoluteString where  urlString.hasPrefix(REDIRECT_URI){
            
            if let q = request.URL?.query{
            
                print(q)
                //http://www.baidu.com/?code=3199d3a955a1aac01b9f03e5616f1ed5
                let code = q.substringFromIndex("code=".endIndex)
                getUserAccount(code)
               // print(code)
            }
       // print(urlString)
            
        } 
        
        return true
    }
}

extension ZPOauthViewController{

    
    func getUserAccount(code:String){
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
 
   
        let params = [
        
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
            
        ]

        CZNetworkTools.sharedTools.request(CZRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            
            if error != nil{
                print(error)
                return
            }
            
            //print("成功\(response)")
            // 在 if let 或者guard 都是对可选值的进行判断 那么 转类型的时候一般都是 '?'
            guard let dataDic = response as? [String: AnyObject] else{
                print("返回的数据不是一个字典")
                return
            }
            
            let account = ZPUserAccount(dict: dataDic)
            
            self.getUserInfo(account)
            
        }
    }
        //获取数据
        func getUserInfo(account:ZPUserAccount){
        
            //请求url
            let urlString = "https://api.weibo.com/2/users/show.json"
            //请求参数
            let params = ["access_token":account.access_token!,
            
                "uid":account.uid!
            ]
            
            CZNetworkTools.sharedTools.request(CZRequestMethod.GET, urlString: urlString, params: params) { (response, error) -> () in
                
                //判断是否有错误
                if error != nil{
                
                    print(error)
                    return
                }
                
                //判断可选值
                guard let dataDict = response as? [String:AnyObject] else{
                
                
                    return
                }
               // 对我们的account 的头像和昵称赋值
                account.avatar_large = dataDict["avatar_large"] as? String
                account.screen_name = dataDict["screen_name"] as?String
                
                // 对用户数据进行保存
                ZPUserAccountTools.sharedTools.saveUserAccount(account)
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    //发送通知切换控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchDefaultVcNSNotification, object: nil)
                })
                
                
            }
            
        }
        
    }
